import json
import datetime
from django.core.paginator import Paginator
from django.db.models import Q
from homes.models import Area, House, Facility , HouseImage
from homes.response_code import RETCODE
from orders.models import Order
from utils.views import LoginRequiredJSONMixin
from django.views import View
from django import http
from .models import HouseImage
# 导入房屋存储storage
from utils.image_storage import storage, storage_img

# api/v1.0/areas/  城区列表
class AreaListView(View):
    """城区列表"""
    def get(self,request):
        areas = Area.objects.all()

        # 序列化
        data = []
        for area in areas:
            data.append({
                "aid":area.id,
                "aname":area.name
            })

        return http.JsonResponse({"errmsg": "获取成功", "errno": RETCODE.OK, "data": data})


# api/v1.0/houses  添加房源
class HomeSourceView(LoginRequiredJSONMixin,View):
    """房源部分"""

    def post(self, request):
        """发布房源"""
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        price = int(json_dict.get('price'))
        area_id = json_dict.get('area_id')
        address = json_dict.get('address')
        room_count = json_dict.get('room_count')
        acreage = json_dict.get('acreage')
        unit = json_dict.get('unit')
        capacity = json_dict.get('capacity')
        beds = json_dict.get('beds')
        deposit = int(json_dict.get('deposit'))
        min_days = json_dict.get('min_days')
        max_days = json_dict.get('max_days')
        facility = json_dict.get('facility')



        # 校验参数
        if not all([title,price,area_id,address,room_count,acreage,unit,capacity,beds,deposit,min_days,max_days,facility]):
            return http.JsonResponse({'errno': 0, 'errmsg': '缺少参数'})

        if min_days>max_days:
            return http.JsonResponse({'errno': -1, 'errmsg': '入住天数输入有误'})


        # 保存参数
        try:
            address = House.objects.create(
                user=request.user,
                title=title,
                price = price,
                area_id = area_id,
                address = address,
                room_count = room_count,
                acreage = acreage,
                unit = unit,
                capacity = capacity,
                beds = beds,
                deposit = deposit,
                min_days = min_days,
                max_days = max_days,

            )

            address.facility.add(*[int(i) for i in facility])
        except Exception as e:
            return http.JsonResponse({'errno': RETCODE.DBERR, 'errmsg': '新增地址失败'})

        # 返回参数
        house_id = address.id
        data = {"house_id":house_id}
        return http.JsonResponse({"errno": RETCODE.OK,"errmsg":"发布成功","data":data})

    # def get(self,request):
    #
    #     aid = request.GET.get('aid')
    #     start = request.GET.get('sd')
    #     end = request.GET.get('ed')
    #     sk = request.GET.get('sk')
    #
    #     try:
    #         if start:
    #             sd = datetime.strptime(start,"%Y-%m-%d")
    #         if start:
    #             ed = datetime.strptime(end,"%Y-%m-%d")
    #     except:
    #         return http.HttpResponseForbidden('日期参数有误')
    #
    #     try:
    #         p = request.GET.get('p')
    #     except:
    #         p = 1
    #
    #     try:
    #         if aid:
    #             id = int(aid)
    #             # area = Area.objects.get(id=id)
    #     except:
    #         return http.HttpResponseForbidden('区域信息有误')
    #
    #     if start and end:
    #         # 查询冲突的订单
    #         chongtu_order = Order.objects.filter(Q(begin_date__lt=end) & Q(end_date__gt=start))
    #
    #     elif start:
    #
    #         # 查询冲突的订单
    #         chongtu_order = Order.objects.filter(Q(end_date__gt=start))
    #
    #     elif end:
    #         chongtu_order = Order.objects.filter(Q(begin_date__lt=end))
    #
    #     else:
    #         chongtu_order = None
    #
    #     if chongtu_order:
    #         # 从订单中获取冲突的房源ｉｄ
    #         chongtu_house_ids = [order.house_id for order in chongtu_order]
    #
    #         if chongtu_house_ids:
    #             # 满足条件的房屋集合
    #             houseset = House.objects.exclude(id__in=chongtu_house_ids)
    #
    #     else:
    #        houseset = House.objects.all()
    #
    #     # 区域条件
    #     if aid:
    #         houseset = houseset.filter(area_id=aid)
    #
    #     print([i.id for i in houseset])
    #     # 查询数据库
    #     # 补充排序条件
    #     if sk == 'booking':
    #         queryset_data = houseset.order_by('-order_count')
    #     elif sk == 'price-inc':
    #         queryset_data = houseset.order_by('price')
    #
    #     elif sk == 'price-desc':
    #         queryset_data = houseset.order_by('-price')
    #
    #     else:
    #         queryset_data = houseset.order_by('-create_time')
    #
    #     # 创建分页器：每页N条记录
    #     paginator = Paginator(queryset_data, 3)
    #     # 获取每页商品数据
    #     page_house = paginator.page(p)
    #     # 获取列表页总页数
    #     total_page = paginator.num_pages
    #
    #     house_info = []
    #     res_data = {
    #         "data": {"houses": house_info, "total_page": total_page},
    #         "errmsg": "请求成功",
    #         "errno": "0"
    #     }
    #
    #     for i in page_house:
    #         ctime = i.create_time.strftime("%Y-%m-%d")
    #         house_info.append({
    #             "address": i.address,
    #             "area_name": i.area.name,
    #             "ctime": ctime,
    #             "house_id": i.id,
    #             "img_url": 'http://q18unh765.bkt.clouddn.com/'+i.index_image_url,
    #             "order_count": i.order_count,
    #             "price": i.price,
    #             "room_count": i.room_count,
    #             "title": i.title,
    #             "user_avatar": i.user.avatar.url
    #         })
    #
    #     return http.JsonResponse(res_data)

# api/v1.0/user/houses/  我的房屋列表
class HomeListView(LoginRequiredJSONMixin,View):
    """我的房屋列表"""
    def get(self,request):

        try:
            user = request.user
            houses = user.houses.all()
        except Exception as e:
            return http.JsonResponse({'errno': RETCODE.DBERR, 'errmsg': '用户没有房屋信息'})

        houses_list = []
        if houses:
            for house in houses:
                houses_list.append({
                    "address":house.address,
                    "area_name":house.area.name,
                    "ctime":house.create_time.date(),
                    "house_id":house.id,
                    "img_url":'http://q18unh765.bkt.clouddn.com/'+house.index_image_url,
                    "order_count":house.order_count,
                    "price":house.price,
                    "room_count":house.room_count,
                    "title":house.title,
                    "user_avatar":'http://q17gq831r.bkt.clouddn.com/' + str(user.avatar),
                })

        return http.JsonResponse({"data":{"houses": houses_list},"errmsg": "ok","errno": "0"})


# api/v1.0/houses/index/   首页房屋推荐
class IndexHomeView(View):
    """首页房屋推荐"""

    def get(self,request):
        # www_url = 'http://q17gq831r.bkt.clouddn.com/'
        data = []
        houses = House.objects.all().order_by('-create_time')[:5]
        for house in houses:
            data.append({
                "house_id":house.id,
                "img_url":'http://q18unh765.bkt.clouddn.com/'+ house.index_image_url,
                "title":house.title
            })
        return http.JsonResponse({"data": data,"errmsg": "OK","errno": "0"})

# api/v1.0/houses/  房屋搜索
class EshouseView(View):
    # 房屋数据搜索
    def get(self, request):

        aid = request.GET.get('aid')
        start = request.GET.get('sd')
        end = request.GET.get('ed')
        sk = request.GET.get('sk')

        try:
            if start:
                sd = datetime.datetime.strptime(start,"%Y-%m-%d").date()
            if end:
                ed = datetime.datetime.strptime(end,"%Y-%m-%d").date()
        except:
            return http.HttpResponseForbidden('日期参数有误')

        try:
            p = request.GET.get('p')
        except:
            p = 1

        try:
            if aid:
                id = int(aid)
                area = Area.objects.get(id=id)
        except:
            return http.HttpResponseForbidden('区域信息有误')

        if start and end:
            # 查询冲突的订单
            chongtu_order = Order.objects.filter(Q(begin_date__lt=end) & Q(end_date__gt=start))

        elif start:

            # 查询冲突的订单
            chongtu_order = Order.objects.filter(Q(end_date__gt=start))

        elif end:
            chongtu_order = Order.objects.filter(Q(begin_date__lt=end))

        else:
            chongtu_order = None

        if chongtu_order:
            # 从订单中获取冲突的房源ｉｄ
            chongtu_house_ids = [order.house_id for order in chongtu_order]

            if chongtu_house_ids:
                # 满足条件的房屋集合
                houseset = House.objects.exclude(id__in=chongtu_house_ids)

        else:
            houseset = House.objects.all()

        # 区域条件
        if aid:
            houseset = houseset.filter(area_id=aid)
        else:
            houseset = houseset

        print([i.id for i in houseset])
        # 查询数据库
        # 补充排序条件
        if sk == 'booking':
            queryset_data = houseset.order_by('-order_count')
        elif sk == 'price-inc':
            queryset_data = houseset.order_by('price')

        elif sk == 'price-des':
            queryset_data = houseset.order_by('-price')

        else:
            queryset_data = houseset.order_by('-create_time')

        # 创建分页器：每页N条记录
        paginator = Paginator(queryset_data, 3)
        # 获取每页商品数据
        page_house = paginator.page(p)
        # 获取列表页总页数
        total_page = paginator.num_pages

        house_info = []
        for i in page_house:
            ctime = i.create_time.strftime("%Y-%m-%d")
            house_info.append({
                "address": i.address,
                "area_name": i.area.name,
                "ctime": ctime,
                "house_id": i.id,
                "img_url": 'http://q18unh765.bkt.clouddn.com/'+i.index_image_url,
                "order_count": i.order_count,
                "price": i.price,
                "room_count": i.room_count,
                "title": i.title,
                "user_avatar": 'http://q17gq831r.bkt.clouddn.com/'+str(i.user.avatar)
            })

        res_data = {
            "data": {"houses": house_info, "total_page": total_page},
            "errmsg": "请求成功",
            "errno": "0"
        }
        return http.JsonResponse(res_data)

# api/v1.0/houses/(?P<house_id>\d+)/  房屋详情
class DetailView(View):
    """房屋详情页面"""
    def get(self,request,house_id):
        house = House.objects.get(id=house_id)
        orders=house.order_set.all()
        # 返回的数据
        comments = []
        for i in orders:
            comments.append({
                "comment": i.comment,
                "ctime": i.create_time.date(),
                "user_name": i.user.real_name
            })


        facilities = [i.id for i in house.facility.all()]

        img_urls = []
        for i in house.houseimage_set.all():
            img_urls.append('http://q18unh765.bkt.clouddn.com/'+str(i.url))
        # img_urls = img_urls
        print(type(img_urls))
        data  = {
            "house":{
                "acreage": house.acreage,
                "address": house.address,
                "beds": house.beds,
                "capacity": house.capacity,
                "comments": comments,
                "deposit": house.deposit,
                "facilities": facilities,
                "hid": house.id,
                "img_urls": img_urls,
                "max_days": house.max_days,
                "min_days": house.min_days,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                "unit": house.unit,
                "user_avatar": 'http://q17gq831r.bkt.clouddn.com/'+ house.user.avatar.url,
                "user_id": house.user.id,
                "user_name": house.user.username
            },
            "user_id": request.user.id,
        }
        return http.JsonResponse({"data": data,"errmsg": "OK","errno": RETCODE.OK})


# api/v1.0/houses/(?P<house_id>\d+)/images  上传房屋图片
class UpdateHouseImage(LoginRequiredJSONMixin, View):

    def post(self, request, house_id):
        # 判断是否传入图片
        house_image = request.FILES.get('house_image')
        if house_image is None:
            return http.JsonResponse({'error': '-1', 'errmsg': "没有图片"})
        image_data = house_image.file.getvalue()
        #上传七牛云
        try:
            ret_file_key = storage_img(image_data)
            print(ret_file_key)
        except Exception as e:
            print(e)

        #  查询House模型类中有没有图片,没有则保存在house_image中
        house = House.objects.get(id=house_id)
        if house.index_image_url=='':
            house.index_image_url = ret_file_key
            house.save()
            # HouseImage.objects.create(house=house,url=ret_file_key)
            domain_url = 'http://q18unh765.bkt.clouddn.com/'
            url = domain_url + str(house.index_image_url)
            print(url)

            data = {"url": url}
            print(data)
            return http.JsonResponse({"errno": "0", "errmsg": "图片上传成功", "data": data})


        else:
            house_img=HouseImage(house=house,url=ret_file_key)
            house_img.save()
            domain_url = 'http://q18unh765.bkt.clouddn.com/'
            url = domain_url + str(house_img.url)
            print(url)

            data = {"url": url}
            print(data)
            return http.JsonResponse({"errno": "0", "errmsg": "图片上传成功", "data": data})

